<?php

use console\db\Migration;
use yii\helpers\ArrayHelper;
use yii\helpers\Console;

/**
 * 初始化类型数据
 * 
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class m200110_000110_d_category extends Migration {

    /**
     * @inheritdoc
     */
    public $tableName = '{{%category}}';

    /**
     * @inheritdoc
     */
    public function safeUp() {
        if (!$this->isExistsTable($this->tableName)) {
            return false;
        }
        $this->truncateTable($this->tableName);
        $this->compact = true;
        $data = $this->getData('category.json');
        foreach ($data as $name => $item) {
            if (!is_array($item)) {
                continue;
            }
            $this->insert($this->tableName, [
                'name' => $name,
                'status' => 10,
                'created_at' => time(),
                'updated_at' => time(),
            ]);
            if (empty($item)) {
                continue;
            }
            $parentId = $this->db->getLastInsertID();
            $this->batchCreate($item, $parentId);
        }
    }

    /**
     * @inheritdoc
     */
    protected function batchCreate($data, $parentId = 0) {
        $count = count($data);
        Console::startProgress($i = 0, $count);
        foreach ($data as $name => $item) {
            $i++;
            Console::updateProgress($i, $count);
            if (!is_numeric($name)) {
                $this->insert($this->tableName, [
                    'parent_id' => $parentId,
                    'name' => $name,
                    'status' => 10,
                    'created_at' => time(),
                    'updated_at' => time(),
                ]);
                if (!empty($item)) {
                    $this->batchCreate($item, $this->db->getLastInsertID());
                }
            } else {
                $this->insert($this->tableName, [
                    'parent_id' => $parentId,
                    'name' => $item,
                    'status' => 10,
                    'created_at' => time(),
                    'updated_at' => time(),
                ]);
            }
        }
        Console::endProgress("update done." . PHP_EOL);
    }

}
